<template>
  <div class="more_list">
    <el-dropdown trigger="click" @command="moreHandleCommand" @visible-change="teamInfoClick"
      popper-class="more_list_team">
      <div class="iconBox"><svg-icon icon-class="more" /></div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item class="Dropdown_item_menu">
            <el-popover placement="right-start" :width="280" trigger="hover">
              <template #reference>
                <div>
                  <svg-icon icon-class="info" class="icon_size" />
                  <span>{{ $t('teamDoc.teamInfo') }}</span>
                  <el-icon class="icon_size2">
                    <ArrowRight />
                  </el-icon>
                </div>
              </template>
              <template #default>
                <div class="team_info_box">
                  <!-- 所属 -->
                  <div class="info_box">
                    <div class="title_box">
                      <svg-icon icon-class="qiyeguanli" class="icon_size" />
                      <span class="title">{{ $t('teamDoc.subjection') }}</span>
                    </div>
                    <div class="row_info">
                      <div class="iconbg">
                        <svg-icon icon-class="zu" />
                      </div>
                      <div>
                        <span>{{ teamInfo.ownerDept }}/</span>
                        <span class="text_color">{{ teamInfo.ownerName }}</span>
                      </div>
                    </div>
                  </div>
                  <!-- Team Name -->
                  <div class="info_box">
                    <div class="title_box">
                      <svg-icon icon-class="ganyan" class="icon_size" />
                      <span class="title">{{ $t('teamDoc.teamName') }}</span>
                    </div>
                    <div class="row_info">
                      <svg-icon icon-class="xiangmutuandui" class="icon_size" />
                      <div>
                        <span class="text_color">{{ teamInfo.teamName }}</span>
                      </div>
                    </div>
                  </div>
                  <!-- Members -->
                  <div class="info_box">
                    <div class="title_box">
                      <svg-icon icon-class="user" class="icon_size" />
                      <span class="title">{{ $t('teamDoc.member') }}</span>
                    </div>
                    <div class="row_info" style="justify-content: space-between;">
                      <div class="people_box">
                        <div v-for="item in teamInfo.teamMember.slice(0, 3)" :key="item.userId" class="people">
                          <span>{{ item.nickname ? item.nickname.slice(-2) : "" }}</span>
                        </div>
                      </div>
                      <div>
                        <span class="text_color">{{ teamInfo.teamMember.length }}</span>
                        <span>人</span>
                      </div>
                    </div>
                  </div>
                  <!-- Description -->
                  <div class="info_box">
                    <div class="title_box">
                      <svg-icon icon-class="tiaocha" class="icon_size" />
                      <span class="title">{{ $t('teamDoc.describe') }}</span>
                    </div>
                    <div class="row_info">
                      <span>{{ teamInfo.instructions || "无" }}</span>
                    </div>
                  </div>
                  <div class="info_box">
                    <div class="people_box" style="font-size:10px">
                      <div class="people">
                        <span style="font-size:10px">{{ teamInfo.ownerName ? teamInfo.ownerName.slice(0, 1) : ""
                          }}</span>
                      </div>
                      <div class="text_color" style="margin:0 12px 0 5px">{{ teamInfo.ownerName }}</div>
                      <div class="create_time">{{ $t('teamDoc.generated') }}{{
                        moment(teamInfo.createTime).format("YYYY-MM-DD hh:mm") }}</div>
                    </div>
                  </div>
                </div>
              </template>
            </el-popover>
          </el-dropdown-item>
          <el-dropdown-item class="Dropdown_item_menu " command="role">
            <svg-icon icon-class="peoples" class="icon_size" />
            <span>{{ $t('teamDoc.roleMenu') }}</span>
          </el-dropdown-item>
          <el-dropdown-item class="Dropdown_item_menu border_bottom" command="member">
            <svg-icon icon-class="user" class="icon_size" />
            <span>{{ $t('teamDoc.memberMenu') }}</span>
          </el-dropdown-item>
          <el-dropdown-item class="Dropdown_item_menu " command="info">
            <svg-icon icon-class="edit" class="icon_size" />
            <span>{{ $t('teamDoc.baiscInfo') }}</span>
          </el-dropdown-item>

          <el-dropdown-item class="Dropdown_item_menu " command="MyCategory">
            <el-icon style="margin-right: 8px;">
              <Plus />
            </el-icon>
            <span>{{ $t('teamDoc.addMyType') }}</span>
          </el-dropdown-item>

          <el-dropdown-item class="Dropdown_item_menu border_bottom" command="delete">
            <svg-icon icon-class="trash" class="icon_size" />
            <span>{{ $t('teamDoc.recycleBin') }}</span>
          </el-dropdown-item>
          <el-dropdown-item class="Dropdown_item_menu " command="moreset">
            <svg-icon icon-class="more" class="icon_size" />
            <span>{{ $t('teamDoc.moreSetting') }}</span>
          </el-dropdown-item>
        </el-dropdown-menu>

      </template>
    </el-dropdown>
    <!-- 新增分类 -->
    <el-dialog @open="handleOpenClassifyDialog" :title="$t('teamDoc.selectionCategory')" v-model="dialogClassify"
      width="30%" :before-close="handleClose" append-to-body>
      <el-form ref="form" :model="formClassify" label-width="150px">
        <el-form-item :label="$t('teamDoc.categoryName')">
          <el-select v-model="formClassify.type_id" ref="typeSelect" multiple @change="onUserSelect"
            :placeholder="$t('teamDoc.plzType')">
            <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { apiTeamGetInformation } from "@/api/teamKnowdge/teamDocApi"
import { apiteamType, apiTeamRelevanceType, apiDeleteTeamRelevanceType } from "@/api/teamKnowdge/teamclassifyApi"
import useUserStore from '@/store/modules/user'
import moment from "moment"
const dialogClassify = ref(false)
const typeList = ref([])
const userStore = useUserStore()
const router = useRouter()
interface TeamInfo {
  ownerDept: string
  ownerName: string
  teamName: string
  teamMember: { userId: string; nickname: string, }[]
  instructions: string,
  createTime: any
}

const teamInfo = ref<TeamInfo>({
  ownerDept: '',
  ownerName: '',
  teamName: '',
  teamMember: [],
  instructions: '',
  createTime: ''
})
const formClassify = reactive({
  id: "",
  name: "",
  type_id: [] as string[]
})

const hasUserInteracted = ref(false)
interface RowItem {
  id: string,
  headNodeId: string,
  types: []
  // Add other properties as needed
}

const props = defineProps<{
  rowItem: RowItem
}>()

const getTeamInfo = async () => {
  const res = await apiTeamGetInformation({
    id: props.rowItem.id
  })
  if (res.code == 200) {
    teamInfo.value = res.data
  }
}
const moreHandleCommand = (command: string) => {
  if (command == "member") {
    router.push(`/newUi/teamKnowdge/teamUser?headNodeId=${props.rowItem.headNodeId}&teamId=${props.rowItem.id}`)
  }
  if (command == "role") {
    router.push(`/newUi/teamKnowdge/teamRole?headNodeId=${props.rowItem.headNodeId}&teamId=${props.rowItem.id}`)
  }
  if (command == "info") {
    router.push(`/newUi/teamKnowdge/teamInfo?headNodeId=${props.rowItem.headNodeId}&teamId=${props.rowItem.id}`)
  }
  if (command == "delete") {
    router.push(`/newUi/teamKnowdge/teamTrash?headNodeId=${props.rowItem.headNodeId}&teamId=${props.rowItem.id}`)
  }
  if (command == "moreset") {
    router.push(`/newUi/teamKnowdge/teamSetting?headNodeId=${props.rowItem.headNodeId}&teamId=${props.rowItem.id}`)
  }
  if (command == "MyCategory") {
    // this.$refs.add.dialogClassify = true;
    let ids = []
    props.rowItem.types.forEach((item: { id: string | null }) => {
      if (item && item.id != null) {
        ids.push(item.id) // Add only non-null item.id values to the ids array
      }
    })
    ids = [...new Set(ids)]

    dialogClassify.value = true
    formClassify.type_id = ids
  }
}
const teamInfoClick = (e) => {
  if (e) {
    getTeamInfo()
  }
}
const handleOpenClassifyDialog = () => {
  hasUserInteracted.value = false
  obtainData()
}
const handleClose = (done) => {
  ElMessageBox.confirm('确认关闭？').then((_ => {
    done()
    emit("refreshData")
  }))
}
const obtainData = () => {
  apiteamType().then((res) => {
    if (res.code == 200) {
      typeList.value = res.data.rows
    }

  })
}
const onUserSelect = () => {
  hasUserInteracted.value = true
}
const emit = defineEmits(['refreshData'])

watch(() => formClassify.type_id, (newVal, oldVal) => {
  if (hasUserInteracted.value) {
    if (newVal.length > oldVal.length) {
      const selectedId = newVal[newVal.length - 1] // Get the most recently added value

      if (!oldVal.includes(selectedId)) {
        let oParam = {
          teamId: props.rowItem.id,
          typeId: selectedId,
          userId: userStore.userId
        }

        // Call the API to add the selected type
        apiTeamRelevanceType(oParam).then((res) => {
          if (res.code == 200) {
            ElMessage.success('添加成功')
            hasUserInteracted.value = false
            // this.$emit("refreshData");
          }
        })
      }
    }
    if (newVal.length < oldVal.length) {
      const removedId = oldVal.find((id) => !newVal.includes(id)) // Find the removed value

      if (removedId) {
        let oParam = {
          teamId: props.rowItem.id,
          typeId: removedId,
          userId: userStore.userId
        }

        // Call the delete API to remove the selected type
        apiDeleteTeamRelevanceType(oParam).then((res) => {
          if (res.code == 200) {
            ElMessage.success('添加成功')
            hasUserInteracted.value = false
            // this.$emit("refreshData");
          }
        })
      }
    }
  }
}, { deep: true })


</script>

<style lang="scss">
.more_list_team {
  .iconBox {
    padding: 5px 8px;
    border-radius: 4px;
    cursor: pointer;

    &:hover {
      color: #6698ff;
      background: rgba(102, 152, 255, 0.1);
    }

    &:focus {
      visibility: visible;
      color: #6698ff;
      background: rgba(102, 152, 255, 0.1);
    }
  }
}

.Dropdown_item_menu {
  //   padding-top: 5px !important;
  //   padding-bottom: 5px !important;
  padding-right: 10px !important;
  font-size: 14px !important;
  line-height: 37px;

  &:hover {
    background-color: #f5f5f5 !important;
    color: #606266;
  }
}

.border_bottom {
  border-bottom: 1px solid #dcdfe6;
}

.el-icon-edit {
  font-size: 16px;
  color: #aaa;
}

.icon_size {
  font-size: 14px;
  color: #aaa;
  margin-right: 10px;
}

.icon_size2 {
  font-size: 14px;
  color: #aaa;
  margin-left: 30px;
}

.team_info_box {
  color: #afafaf;

  .text_color {
    color: #262626;
  }

  .create_time {
    font-size: 12px;
  }

  .info_box {
    margin-bottom: 20px;
  }

  .title_box {
    font-size: 13px;
    margin-bottom: 10px;

    .title {}
  }

  .row_info {
    display: flex;
    align-items: center;
    padding-bottom: 10px;
    margin-left: 12px;
    border-bottom: 1px solid #dddddd;
  }

  .people_box {
    display: flex;
    align-items: center;
    margin-left: 5px;

    .people {
      width: 24px;
      height: 24px;
      border-radius: 12px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 12px;
      background-color: #56abfb;
      margin-right: 3px;

      span {
        transform: scale(0.9, 0.9);
      }
    }
  }

  .iconbg {
    width: 22px;
    height: 22px;
    line-height: 22px;
    border-radius: 10px;
    background-color: #6698ff;
    color: #fff;
    margin: 0px 5px;
    text-align: center;

    .icon_size {
      font-size: 13px;
    }
  }
}
</style>
